The inability to receive a response from the OpenAI API in NextJS is causing frustration

I tried following a tutorial to implement functionality in T, but I am facing issues with getting a response from the API. I am unsure if there has been an update to the OpenAI API that is causing this problem.

Any assistance would be greatly appreciated.

Error

http://localhost:3000/api/chat-gpt net::ERR_ABORTED 500 (Internal Server Error)
onClick @   page.tsx:13
Show 14 more frames

/app/(main)/page.tsx

'use client'
import React from 'react';
import Navbar from './_components/navbar';

const HomePage = () => {
  return ( 
    <div className="w-full min-h-full">
      <Navbar />
      <div className="flex flex-col justify-center">
        <h1 className="text-4xl">Welcome to Mood Palette</h1>
        <button
          onClick={async () => {
            const response = await fetch('/api/chat-gpt', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                message: 'Hello, World!',
              }),
            });
            console.log("Response", response);
          }}
        >
          Create Palette
        </button>
      </div>

    </div>
   );
}
 
export default HomePage;

/app/api/route.ts

import { NextRequest, NextResponse } from "next/server";
import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: `Bearer ${process.env.OPENAI_API_KEY}`,
    project: 'project_id',
});

export async function POST(request: Request) {


    const response = await openai.chat.completions.create({ 
        model: "gpt-3.5-turbo", 
        messages: [
            { role: "system", content: "You are Jarvis from Iron Manl" },
            { role: "user", content: "Who are you?"}
        ],
        temperature: 0,
        max_tokens: 1024,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    });

    return NextResponse.json(response);
}

After following the OpenAI documentation 'getting started' and a tutorial, I encountered issues with the API not responding properly. Any tips on troubleshooting would be helpful.

Answer №1

After reviewing your information, it appears that you are referencing a nonexistent endpoint:

The API file you are looking for should be located at:

/app/api/chat-gpt/route.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Every character entered in JSP should trigger an instant retrieval of the corresponding string in the servlet

Having a JSP file that contains a text field: <form action="someServlet" method=post> <input type ="text" name="user" id="uname"> <button type="submit" id="submit">Submit</button> </form> When typing each letter in the JSP, ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Typescript - any of the types imported from a module

Currently, my code looks like this: import * as Types from '../schema/types'; and I'm looking to achieve something along the lines of: let a: Types; This would signify that a should be one of the various types exported from the file types. ...

Incorporating RecoilRoot into Next.js with the Next.js 13's App router approach architecture

In my Next.js project, I've opted to utilize Recoil for state management. Following the structure of src/app/pages.tsx (app router approach) in Next.js 13 for routing instead of the default _app.tsx method, I'm now faced with the challenge of wra ...

In the event that the get request fails, go ahead and clear the

Currently facing an issue and seeking a solution: I have a game running that retrieves the state of the game periodically. However, if a user logs out, the game ends but continues to send put requests at the set interval. I am exploring options like setti ...

Function in React not being successfully passed down between functional components

I have been accustomed to using class components and now I am transitioning into functional components in order to become more proficient with hooks. However, I have encountered an issue where I am struggling to pass a function from one functional compone ...

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

What are some effective methods for testing internet connectivity?

My CMS operates by pulling large amounts of data using PHP, MySQL, jQuery, Bootstrap, and AJAX. An issue arises when the internet connection is lost, causing problems with displaying and scrolling on the site. I am interested in finding a solution that c ...

The Next.js API has a mysterious parameter that remains undefined

I currently have a component implemented import React, { useEffect } from "react"; import styles from "../styles/success.module.css"; import { useRouter } from "next/router"; import axios from "axios"; const Success ...

Having trouble accessing data from the local storage?

const headers = new Headers({ 'access_token' : accToken, 'Content-Type': 'application/json', }); axios.post(baseURI, data, { headers: headers }) ...

JavaScript, PHP handlers, and CommentBox all work together seamlessly to create

$("#login").click(function(){ $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){ console.log(data); //retrieves data from login box and sends it to the handler, returning a JSON array }); template = $("#hid ...

Is it possible to dispatch an async action when a route changes in React Router and Redux?

I am working on a universal react app with redux and react-router integration. My app has multiple routes such as: /2016 /2015 /2014 /2013 and so on. Each route requires fetching data from an API. Currently, I am using <Link> elements in the Navi ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Enhance your JavaScript code by using the powerful Node.js util.format() method

I have been attempting to enhance the functionality of the node.js util.format function by allowing it to be used as a prototype (for example: "Hello %s".format("World")). Unfortunately, my attempts have all failed. I've tried different formats like: ...

Before the custom font finishes loading, useEffect is triggered

Custom font usage in my app: @font-face { font-family: "Koulen"; src: url("./assets/fonts/Koulen-Regular.ttf") format("truetype"); } body { font-family: "Koulen"; } An issue arises as the useEffect is called ...

Issue with implementing styles on Navbar React component

I'm currently learning Next.js, specifically working with version 10.0.3. In my project, I am using react-bootstrap version 1.4.0 and classnames version 2.2.6. Within my project, I have a component called Navbar that I am trying to style in a certain ...

Cross-Origin Resource Sharing problem impacting a Next.js web application

I've encountered a CORS issue while trying to deploy my Next.js application with Dokku, after previously deploying it without error on Vercel. The problem arises when the Next.js server communicates with a Python Django API through an API gateway. In ...

What is the best way to add a component into a MAP of other components in a React application?

I have a project where I am implementing a MAP function to iterate through an array of objects and present the data using a special Card component. However, I want to include another component called Banner after every second Card element from the loop, an ...