I'm trying to use the OpenAI API to analyze a physics question in my Next.js project. However, when I send a POST request to my API, I receive a 500 Internal Server Error. I've checked the code and confirmed that my API key is valid, but I can't resolve this issue. Below is the code I'm using: Code:
import { NextResponse } from 'next/server';
export async function POST(req) {
const { question } = await req.json();
const result = await analyzeQuestion(question);
return NextResponse.json(result);
}
async function analyzeQuestion(question) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk-xxxxxx', // Replace with your API key
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: 'You are an educational assistant' },
{ role: 'user', content: question },
],
temperature: 0.3,
max_tokens: 500,
}),
});
const data = await response.json();
return data.choices[0]?.message.content || {};
}
Error Received:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
What I have tried: I have checked the API key, tried sending requests with different parameters, and made sure there are no syntax errors in my code. I've also tried restarting the server and checking the logs, but the issue still persists.
Help Request: Can anyone help me figure out the cause of this issue and how to fix the 500 error?