DEV Community

parmarjatin4911@gmail.com
parmarjatin4911@gmail.com

Posted on

Chat GPT API Node.js

Chat GPT API Node.js

npm install openai

ES6

import OpenAI from "openai";

const openai = new OpenAI();

const chatCompletion = await openai.chat.completions.create({
messages: [{ role: "user", content: "Say this is a test" }],
model: "gpt-3.5-turbo",
});

console.log(chatCompletion.choices[0].message.content);

package.json

{
"dependencies": {
"openai": "^4.12.4"
},
"type": "module"
}

CommonJS

const OpenAI = require("openai");

const openai = new OpenAI();

openai.chat.completions.create({
messages: [{ role: "user", content: "Say this is a test" }],
model: "gpt-3.5-turbo",
})
.then(chatCompletion => {
console.log(chatCompletion.choices[0].message.content);
})
.catch(console.error);

Image description

Which is Best?

For New Projects: ES6 is modern and efficient.
For Older Projects: CommonJS is well-supported and easy.
Enter fullscreen mode Exit fullscreen mode

Combined Recommendation: Choose CommonJS for simplicity and legacy support. Choose ES6 for modern features and better optimization.

Top comments (0)