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);
Which is Best?
For New Projects: ES6 is modern and efficient.
For Older Projects: CommonJS is well-supported and easy.
Combined Recommendation: Choose CommonJS for simplicity and legacy support. Choose ES6 for modern features and better optimization.
Top comments (0)