Thank you so much for the feedback. So I’ve re-written the following code as per your instructions :
const { OpenAI } = require(‘openai’);
require(‘dotenv’).config();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const chatCompletion = async (prompt) => {
try {
const response = await openai.chat.completions.create({
model: ‘gpt-3.5-turbo’,
messages: [
{ “role”: “user”, “content”: prompt }
]
});
// Log the whole API response to troubleshoot the format.
console.log('API Response: ', response);
// Check if the expected data exists before trying to access it.
if (response && response.data && response.data.choices && response.data.choices.length > 0) {
let content = response.data.choices[0].message.content;
console.log('This is the response : ', content);
return {
status: 1,
response: content
};
} else {
throw new Error('Unexpected API response format.');
}