OpenAI API error: "Module 'openai' has no exported member 'Configuration'"
Asked Answered
S

4

11

I'm trying to do an API call to the GPT-3.5 API, but anything imported from OpenAI is giving me a has no exported member error.

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 });
    }
}

The error message is:

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

Any idea why?

Sphacelus answered 16/8, 2023 at 22:53 Comment(0)
C
28

Problem

OpenAI NodeJS SDK v4 was released on August 16, 2023, and is a complete rewrite of the SDK. You have v4, but you want to use the code that works with v3.

To check your OpenAI NodeJS SDK version, run the following command:

npm info openai version

Solution 1: Automatic migration

Because there are many fundamental changes in v4, the easiest way to migrate from v3 to v4 is to run the following CLI command:

npm exec openai migrate

It's important to audit the changes, as stated in the official OpenAI v3 to v4 migration guide:

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


Solution 2: Manual migration

• Initialization

// 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,
});

• Creating a chat completion

// 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);

// 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);

• Creating a streaming chat completion (new)

// Old (i.e., OpenAI NodeJS SDK v3)
// Not supported

// New (i.e., OpenAI NodeJS SDK v4)
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);
}

• Creating a completion

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

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

• Creating a transcription (Whisper)

// Old (i.e., OpenAI NodeJS SDK v3)
const response = await openai.createTranscription(
  fs.createReadStream("audio.mp3"),
  "whisper-1"
);

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

• Creating a streaming completion (new)

// Old (i.e., OpenAI NodeJS SDK v3)
// Not supported

// New (i.e., OpenAI NodeJS SDK v4)
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]);
}

• Error handling

// Old (i.e., OpenAI NodeJS SDK v3)
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 (i.e., OpenAI NodeJS SDK v4)
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);
  }
}

• All method name changes:

Old (i.e., v3) New (i.e., v4)
openai.createChatCompletion openai.chat.completions.create
openai.createCompletion openai.completions.create
openai.createTranscription openai.audio.transcriptions.create
openai.createTranslation openai.audio.translations.create
openai.createFineTune openai.fineTunes.create
openai.cancelFineTune openai.fineTunes.cancel
openai.retrieveFineTune openai.fineTunes.retrieve
openai.listFineTunes openai.fineTunes.list
openai.listFineTuneEvents openai.fineTunes.listEvents
openai.createFile openai.files.create
openai.deleteFile openai.files.del
openai.retrieveFile openai.files.retrieve
openai.downloadFile openai.files.retrieveContent
openai.listFiles openai.files.list
openai.deleteModel openai.models.del
openai.listModels openai.models.list
openai.retrieveModel openai.models.retrieve
openai.createImage openai.images.generate
openai.createImageEdit openai.images.edit
openai.createImageVariation openai.images.createVariation
openai.createChatCompletion openai.chat.completions.create
openai.createEmbedding openai.embeddings.create
openai.createModeration openai.moderations.create

• Removed:

  • createAnswer()
  • createClassification()
  • createSearch()
  • listEngines()
  • retrieveEngine()
  • createEdit()
Commorancy answered 23/8, 2023 at 10:46 Comment(1)
Thanks for the detailed answer. The auto migration is very cool: app.grit.io/studio?preset=openai_v4Palladium
A
8

that is v3. you need to migrate to v4. from npm

[!IMPORTANT] Previous versions of this SDK used a Configuration class. See the v3 to v4 migration guide.

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: 'my api key', // defaults to process.env["OPENAI_API_KEY"]
});

migration guide

Agapanthus answered 16/8, 2023 at 23:54 Comment(2)
thank you how would i edit my page.tsx to handle and display the call, sorry first time doing thisSphacelus
pls follow the documentationAgapanthus
E
0

If you dont want to migrate to v4 then u can simply use v3 just type npm i [email protected] in your project terminal

Here is the documentation link https://www.npmjs.com/package/openai/v/3.3.0

Enterotomy answered 23/9, 2023 at 14:20 Comment(0)
P
0

Although this is happening because of v4 you can try in this way

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

It worked in my case

Propeller answered 26/2 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.