-3

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?

1

1 Answer 1

0

If you are using the free trial version of OpenAI, you may encounter limitations that could cause a 500 Internal Server Error.

You could try ‘@ai-sdk/openai’ is not available in the free tier(you might need to configure the provider correctly).

import { openai } from "@ai-sdk/openai";

async function sendMessage(message: string) {
  try {
    const { text } = await generateText({
      model: openai("gpt-4-turbo"), // Uses the GPT-4 Turbo model
      system: "You are an educational assistant",
      prompt: message,
    });
    return text;
  } catch (error) {
    console.error("Error generating text:", error);
    throw new Error("response could not be generated");
  }
}

Or maybe add proper error handling:

async function analyzeQuestion(question) {
  try {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`, // Better to use environment variables
      },
      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,
      }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error?.message || 'Failed to fetch from OpenAI');
    }

    const data = await response.json();
    return data.choices[0]?.message?.content || 'No response from AI';
  } catch (error) {
    console.error('OpenAI API error:', error);
    return { error: error.message };
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.