I am exploring chatGPT API Documentation. I created a following array and sending it to generate response from the ChatGPT API. It works fine.
But whenever I am pushing an object inside that array and then sending it to the ChatGPT API it is showing an error.
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: 'Your OPENAI_API_KEY',
});
const chatGPTProvider = async () => {
try {
const url = 'https://api.openai.com/v1/chat/completions';
let data = [
{ role: 'system', content: 'You are a helpful assistant.' },
{
role: 'user',
content: 'Act as an intelligent AI.',
},
];
// data.push({ role: 'sytem', content: 'Hola GPT' });
// console.log(data);
const resp = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: data,
});
return { status: 'SUCCESS', result: resp.data.choices[0].message };
} catch (ex) {
console.log(ex.message);
return { status: 'ERROR', result: null };
}
};
This code works fine. When you uncomment that push method it starts giving error.
Can you please tell why only pushing data into the array results in error?
Documentation: https://platform.openai.com/docs/api-reference/chat/create?lang=node.js
I am getting the following Error
Error: Request failed with status code 400
at createError (/home/sushant007/Interview-Project/GPT-chatbot/server/node_modules/openai/node_modules/axios/lib/core/createError.js:16:15)
at settle (/home/sushant007/Interview-Project/GPT-chatbot/server/node_modules/openai/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/home/sushant007/Interview-Project/GPT-chatbot/server/node_modules/openai/node_modules/axios/lib/adapters/http.js:322:11)
at IncomingMessage.emit (node:events:524:35)
at endReadableNT (node:internal/streams/readable:1378:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
2
Answers
Only four type of role are possible in ChatGPT API. These are system, user, assistant, or function.
Ref: https://platform.openai.com/docs/api-reference/chat/create#chat/create-role
You need to call
JSON.stringify()
because the ChatGPT API is callingJSON.parse()
on an already-parsed object, which should be throwing an error.The 400 status code probably means malformed or strange syntax that the server can’t parse. So I’m assuming that’s what the problem is, so try the
JSON.stringify()
method.