I am trying to use Openai api with nodejs, I follow the tutorial and want to add a simple gpt text completion feauture using the openai SDK, but I got an error says: /node_modules/openai/core.js:44 const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
It results in a crash of the app, I didn't find out why.
This is the code:
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export const gptResponse = async (req, res) => {
try {
const { message } = req.body;
const getResponse = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful assistant.',
},
{
role: 'user',
content: message,
},
],
});
console.log(getResponse.data.choices[0].message.content);
return res.json(getResponse.data.choices[0].message.content);
} catch (err) {
console.log(err);
return res.status(400).send('Error. Try again.');
}
};
This code will work.
Save as `demo.js'
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const requestData = {
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful assistant.',
},
{
role: 'user',
content: 'Hello!',
},
],
};
async function getGPTResponse() {
try {
const response = await openai.chat.completions.create(requestData);
console.log("Response from OpenAI:", response.choices[0].message.content);
} catch (error) {
console.error("Error:", error.message);
}
}
getGPTResponse();
In package.json
{
"type": "module",
"dependencies": {
"openai": "^4.28.0"
}
}
npm install
node demo.js
You can see the response message's hierarchy
url
POST https://api.openai.com/v1/chat/completions
In body
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
}
API_KEY
Error
Error: 401 You have insufficient permissions for this operation. Missing scopes: model.request
API_KEY
API_KEY