gpt4 book ai didi

javascript - OpenAI API错误: "Module ' openai' has no exported member 'Configuration' "

转载 作者:行者123 更新时间:2023-12-02 05:48:18 27 4
gpt4 key购买 nike

我正在尝试对 GPT-3.5 API 进行 API 调用,但从 OpenAI 导入的任何内容都会出现“没有导出成员”错误。

import { Configuration, OpenAIApi } from "openai";
import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";

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

const openai = new OpenAIApi(configuration);

export async function POST(
req: Request
) {
try {
const { userId } = auth();
const body = await req.json();
const { messages } = body;

if (!userId) {
return new NextResponse("Unauthorised", { status: 401 });
}

if (!configuration.apiKey) {
return new NextResponse("OpenAI API Key not configured", { status: 500 });
}

if (!messages) {
return new NextResponse("Messages are required", { status: 400 });
}

const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages
});

return NextResponse.json(response.data.choices[0].message);

} catch (error) {
console.log("[CONVERSATION_ERROR]", error)
return new NextResponse("Internal error", { status: 500 });
}
}

错误信息是:

Module '"openai"' has no exported member 'Configuration'. Did you mean to use 'import Configuration from "openai"' instead?
 warn ./app/api/conversation/route.ts
Attempted import error: 'Configuration' is not exported from 'openai' (imported as 'Configuration').

Import trace for requested module:
./app/api/conversation/route.ts

./app/api/conversation/route.ts
Attempted import error: 'OpenAIApi' is not exported from 'openai' (imported as 'OpenAIApi').

Import trace for requested module:
./app/api/conversation/route.ts
- error app\api\conversation\route.ts (5:22) @ eval
- error Error [TypeError]: openai__WEBPACK_IMPORTED_MODULE_0__.Configuration is not a constructor
at eval (webpack-internal:///(rsc)/./app/api/conversation/route.ts:11:23)
at (rsc)/./app/api/conversation/route.ts (C:\Users\ctcco\ai-saas\.next\server\app\api\conversation\route.js:312:1)
at __webpack_require__ (C:\Users\ctcco\ai-saas\.next\server\webpack-runtime.js:33:42)
at eval (webpack-internal:///(rsc)/./node_modules/next/dist/build/webpack/loaders/next-app-loader.js?name=app%2Fapi%2Fconversation%2Froute&page=%2Fapi%2Fconversation%2Froute&appPaths=&pagePath=private-next-app-dir%2Fapi%2Fconversation%2Froute.ts&appDir=C%3A%5CUsers%5Cctcco%5Cai-saas%5Capp&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&rootDir=C%3A%5CUsers%5Cctcco%5Cai-saas&isDev=true&tsconfigPath=tsconfig.json&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!:16:109)
at (rsc)/./node_modules/next/dist/build/webpack/loaders/next-app-loader.js?name=app%2Fapi%2Fconversation%2Froute&page=%2Fapi%2Fconversation%2Froute&appPaths=&pagePath=private-next-app-dir%2Fapi%2Fconversation%2Froute.ts&appDir=C%3A%5CUsers%5Cctcco%5Cai-saas%5Capp&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&rootDir=C%3A%5CUsers%5Cctcco%5Cai-saas&isDev=true&tsconfigPath=tsconfig.json&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D! (C:\Users\ctcco\ai-saas\.next\server\app\api\conversation\route.js:302:1)
at __webpack_require__ (C:\Users\ctcco\ai-saas\.next\server\webpack-runtime.js:33:42)
at __webpack_exec__ (C:\Users\ctcco\ai-saas\.next\server\app\api\conversation\route.js:2726:39)
at C:\Users\ctcco\ai-saas\.next\server\app\api\conversation\route.js:2727:28
at Object.<anonymous> (C:\Users\ctcco\ai-saas\.next\server\app\api\conversation\route.js:2730:3)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Module.require (node:internal/modules/cjs/loader:1141:19)
at require (node:internal/modules/cjs/helpers:110:18)
at requirePage (C:\Users\ctcco\ai-saas\node_modules\next\dist\server\require.js:112:75)
at C:\Users\ctcco\ai-saas\node_modules\next\dist\server\load-components.js:80:84
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async loadComponentsImpl (C:\Users\ctcco\ai-saas\node_modules\next\dist\server\load-components.js:80:26)
at async DevServer.findPageComponentsImpl (C:\Users\ctcco\ai-saas\node_modules\next\dist\server\next-server.js:439:36) {
digest: undefined
}
3 | import { NextResponse } from "next/server";
4 |
> 5 | const configuration = new Configuration({
| ^
6 | apiKey: process.env.OPENAI_API_KEY
7 | });
8 |
- warn ./app/api/conversation/route.ts
Attempted import error: 'Configuration' is not exported from 'openai' (imported as 'Configuration').

Import trace for requested module:
./app/api/conversation/route.ts

./app/api/conversation/route.ts
Attempted import error: 'OpenAIApi' is not exported from 'openai' (imported as 'OpenAIApi').

Import trace for requested module:
./app/api/conversation/route.ts
- wait compiling /_error (client and server)...
- warn ./app/api/conversation/route.ts
Attempted import error: 'Configuration' is not exported from 'openai' (imported as 'Configuration').

Import trace for requested module:
./app/api/conversation/route.ts

./app/api/conversation/route.ts
Attempted import error: 'OpenAIApi' is not exported from 'openai' (imported as 'OpenAIApi').

Import trace for requested module:
./app/api/conversation/route.ts
- warn ./app/api/conversation/route.ts
Attempted import error: 'Configuration' is not exported from 'openai' (imported as 'Configuration').

Import trace for requested module:
./app/api/conversation/route.ts

./app/api/conversation/route.ts
Attempted import error: 'OpenAIApi' is not exported from 'openai' (imported as 'OpenAIApi').

Import trace for requested module:
./app/api/conversation/route.ts
- wait compiling /(dashboard)/(routes)/conversation/page (client and server)...
- warn ./app/api/conversation/route.ts
Attempted import error: 'Configuration' is not exported from 'openai' (imported as 'Configuration').

Import trace for requested module:
./app/api/conversation/route.ts

./app/api/conversation/route.ts
Attempted import error: 'OpenAIApi' is not exported from 'openai' (imported as 'OpenAIApi').

Import trace for requested module:
./app/api/conversation/route.ts
- wait compiling...
- warn ./app/api/conversation/route.ts
Attempted import error: 'Configuration' is not exported from 'openai' (imported as 'Configuration').

Import trace for requested module:
./app/api/conversation/route.ts

./app/api/conversation/route.ts
Attempted import error: 'OpenAIApi' is not exported from 'openai' (imported as 'OpenAIApi').

Import trace for requested module:
./app/api/conversation/route.ts

知道为什么吗?

最佳答案

问题

OpenAI NodeJS SDK v4released于2023年8月16日发布,并且是对SDK的完全重写。您有v4 ,但您想使用适用于 v3 的代码.


方案一:自动迁移

因为v4有很多根本性的变化,从 v3 迁移的最简单方法至v4是运行以下 CLI 命令:

npm exec openai migrate

审核更改非常重要,如官方 OpenAI v3 to v4 migration guide 中所述。 :

Be sure to audit its changes: we suggest ensuring you have a cleanworking tree beforehand, and running git add --patch afterwards. Notethat grit.io also offers opt-in automatic fixes powered by AI.


解决方案2:手动迁移

• 初始化

// Old
import { Configuration, OpenAIApi } from "openai";

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

// New
import OpenAI from 'openai';

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

• 创建聊天完成

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

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

• 创建流式聊天完成(新)

// Old
// Not supported

// New
const stream = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{"role": "user", "content": "Hello!"}],
stream: true,
});
for await (const part of stream) {
console.log(part.choices[0].delta);
}

• 创建完成

// Old
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: "This story begins",
max_tokens: 30,
});
console.log(completion.data.choices[0].text);

// New
const completion = await openai.completions.create({
model: "text-davinci-003",
prompt: "This story begins",
max_tokens: 30,
});
console.log(completion.choices[0].text);

• 创建转录(耳语)

// Old
const response = await openai.createTranscription(
fs.createReadStream("audio.mp3"),
"whisper-1"
);

// New
const response = await openai.audio.transcriptions.create({
model: 'whisper-1',
file: fs.createReadStream('audio.mp3'),
});

• 创建流式完成(新)

// Old
// Not supported

// New
const stream = await openai.completions.create({
model: "text-davinci-003",
prompt: "This story begins",
max_tokens: 30,
stream: true,
});
for await (const part of stream) {
console.log(part.choices[0]);
}

• 错误处理

// Old
try {
const completion = await openai.createCompletion({...});
} catch (error) {
if (error.response) {
console.log(error.response.status); // e.g. 401
console.log(error.response.data.message); // e.g. The authentication token you passed was invalid...
console.log(error.response.data.code); // e.g. 'invalid_api_key'
console.log(error.response.data.type); // e.g. 'invalid_request_error'
} else {
console.log(error);
}
}

// New
try {
const response = await openai.completions.create({...});
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error(error.status); // e.g. 401
console.error(error.message); // e.g. The authentication token you passed was invalid...
console.error(error.code); // e.g. 'invalid_api_key'
console.error(error.type); // e.g. 'invalid_request_error'
} else {
// Non-API error
console.log(error);
}
}

• 所有方法名称更改

<表类=“s-表”><标题>旧(即 v3 )新(即 v4 ) <正文>openai.createChatCompletionopenai.chat.completions.createopenai.createCompletionopenai.completions.createopenai.createTranscriptionopenai.audio.transcriptions.createopenai.createTranslationopenai.audio.translations.createopenai.createFineTuneopenai.fineTunes.createopenai.cancelFineTuneopenai.fineTunes.cancelopenai.retrieveFineTuneopenai.fineTunes.retrieveopenai.listFineTunesopenai.fineTunes.listopenai.listFineTuneEventsopenai.fineTunes.listEventsopenai.createFileopenai.files.createopenai.deleteFileopenai.files.delopenai.retrieveFileopenai.files.retrieveopenai.dow​​nloadFileopenai.files.retrieveContentopenai.listFilesopenai.files.listopenai.deleteModelopenai.models.delopenai.listModelsopenai.models.listopenai.retrieveModelopenai.models.retrieveopenai.createImageopenai.images.generateopenai.createImageEditopenai.images.editopenai.createImageVariationopenai.images.createVariationopenai.createChatCompletionopenai.chat.completions.createopenai.createEmbeddingopenai.embeddings.createopenai.createModerationopenai.moderations.create

• 已删除

  • createAnswer()
  • createClassification()
  • createSearch()
  • listEngines()
  • retrieveEngine()
  • createEdit()

关于javascript - OpenAI API错误: "Module ' openai' has no exported member 'Configuration' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76917525/

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