0

I want to integrate the ChatGPT API (i.e., GPT-3.5 API) into my application. I tried many ways, but I did not find a solution to my error.

My code:

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

Error:

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

I tried to search for information about this on the Internet, but did not find anything.

Rok Benko
  • 14,265
  • 2
  • 24
  • 49
Nikita
  • 11
  • 2

1 Answers1

0

Problem

If you're using the latest OpenAI NodeJS SDK version (i.e., v4), you need to adapt the code because v4 differs from v3 quite significantly. The code you're currently using works with v3 but not with v4. See the changes below.

Solution

Initialization

Change this...

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

...to this.

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

Change this...

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

...to this.

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

Note: SDK v4 was released on August 16, 2023, and is a complete rewrite of the SDK. See the v3 to v4 migration guide.

Rok Benko
  • 14,265
  • 2
  • 24
  • 49
  • @Nikita Please [accept](https://meta.stackexchange.com/a/5235) my answer if this solves your problem. :) – Rok Benko Aug 28 '23 at 15:12