I’ve build a website with a frontend and a backend. I’m doing a survey, and I send the questions asked to the backend. Here I want to use the API but I’ve encountered a problem, here is my code and the output of the Terminal:
app.post('/submit-data', async(req, res) => {
const formData = req.body;
const prompt = createPromptForOpenAI(formData, companyCriteria);
try {
const openaiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer [OPENAI_API_KEY]`,
},
body: JSON.stringify({
"model": "gpt-3.5-turbo",
"usage": {
"total_tokes": 300
},
"choices": [{
"message": {
"role": "user",
"content": prompt,
},
"finish_reason": "stop",
"index": 0
}]
})
});
const data = await openaiResponse.json();
console.log(data);
if (data.choices && data.choices.length > 0) {
res.json({
openAIResponse: data.choices[0].text
});
} else {
console.error("OpenAI API response is missing 'choices':", data);
res.status(500).send('Error processing OpenAI API response');
}
}
})
And this is the Terminal output:
Server running on port ${PORT}
{
error: {
message: "'messages' is a required property",
type: 'invalid_request_error',
param: null,
code: null
}
}
OpenAI API response is missing 'choices': {
error: {
message: "'messages' is a required property",
type: 'invalid_request_error',
param: null,
code: null
}
}
Thank you very much for helping me if you can!
I’ve read through the OpenAI API documentation, but I don’t get what I should change. I changed that the choices is invloved but that didnt really do anything.