I am using openai API on javascript. Below is my code.
require('dotenv').config();
const OpenAI_Api = process.env.OpenAIApi || 'Mykey';
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: OpenAI_Api
});
const openai = new OpenAIApi(configuration);
const createChatCompletion = async () => {
try {
const response = await openai.createChatCompletion({
model: 'gpt-4.0',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Who won the world series in 2020?' },
{ role: 'assistant', content: 'The Los Angeles Dodgers won the World Series in 2020.' },
{ role: 'user', content: 'Where was it played?' },
{ role: 'assistant', content: 'The World Series was played in Arlington, Texas at the Globe Life Field.' },
],
});
console.log(response.choices[0].message.content); // Display the generated response
} catch (error) {
console.error('Error creating chat completion:', error);
}
};
createChatCompletion();
It is saved in chatgpt.js. However, when I run node chatgpt.js, I receive the error.
const configuration = new Configuration({
^
TypeError: Configuration is not a constructor
at Object. (D:OneDrive – The University of NottinghamESR1workKnowledge graphdoctorai_ui_gpt3_testchatgpt.js:7:23)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
2
Answers
Your implementation is based on v3 but you’re using v4. This comes with some changes.
First of, the initialization is a bit different, there is no use of a
Configuration
object anymore. Furthermore theopenai.createChatCompletion
is moved toopenai.chat.completions.create
.I’ve reflected these changed in the code you’ve provided.
What you’re trying to use worked with the OpenAI Node.js SDK <
v4
.As you said, you’re using
v4.26.0
, so the following is the correct initialization:But you also made some other mistakes:
createChatCompletion
, which works with <v4
)gpt-4.0
, which does not exist)The following is the correct full code: