skip to Main Content

I’m creating a AI chat using OpenAI API, i following this tutorial but the thing is when i made the call to the api/chat/sendMessage.js i get the 404 error, idk what to do, i made several OpenAI keys and still not working, here is te code in sendMessage.js

import { OpenAIEdgeStream } from "openai-edge-stream";


export const runtime = 'edge';

export default async function handler(req){
    try{
    const {message} = req.json;
    const stream= await OpenAIEdgeStream('https://api.openai.com/v1/chat/completions',
    {
        headers:{'content-type': 'application/json',
        Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
        },
        method: "POST",
        body: JSON.stringify({
            model: "gpt-3.5-turbo",
            messages: [{content: message, role: "user"}],
            stream: true
        }) 
    }
    );
    return new Response(stream);
    
    }catch(e){
        console.log("Un error ha ocurrido al enviar el mensaje", e);
    }
}

And the page.tsx where i send the form(the message the user writes) to the api

"use client";
import Image from 'next/image';
import EmptyState from './components/EmptyState';
import Historial from './components/Historial';
import { useState } from 'react';
import {streamReader} from "openai-edge-stream";

export default function Home() {
  const [messageText, setMessageText] = useState("");
  
  const handleSumbit = async (e) => {
    e.preventDefault();
    console.log("MessageText:", messageText);
    const response = await fetch("/api/chat/sendMessage", {
        method:'POST',
        headers:{
            'content-type': 'application/json',
        },
        body: JSON.stringify({message: messageText}),
        
    });
    
    const data= response.body;
    //const data = await response.json();
    if(!response.ok){
      throw new Error("No sirve la api alv");   
    }
    const reader= data.getReader();
    await streamReader(reader, (message) =>{
        console.log("Message AI:", message)
    });
}

  return (
    <>
    <main className="h-full">
      
      <div className="flex flex-row h-full">
      <div className="w-[30px]">
          <Historial /> 
      </div>
      <div className=" lg:pl-[200px] w-full flex flex-col h-full " >
        <div className="flex-1 overflow-y-auto">
            Body!</div>
            <div >
            <form onSubmit={handleSumbit}> {/* style del form*/}
                <fieldset className="flex gap-2">
                    <textarea 
                    value={messageText}
                    onChange={(e) => setMessageText(e.target.value)}
                    placeholder="Send a Message..." 
                    className="w-full resize-none rounded-md bg-white p-2 text-black border-none focus:outline-none"></textarea>
                    <button type="submit" className="rounded-full p-2 bg-[#2c4277] cursor-pointer hover:bg-[#23355e] transition w-[37px] h-[37px]">
                    <Image src="/enviar.png" alt="enviar" width={35} height={35} />
                    </button>
                </fieldset>
                
            </form>
        </div>
      </div>
      </div>
    </main>
    </>
  );
}

I tried change to response.json() and didn’t work, i change several API keys and also give the 404.

2

Answers


  1. Have you generated other Key in the OpenAI plataform? Maybe you copied wrong

    Login or Signup to reply.
  2. you have a typo here:

    const {message} = req.json(); // missing ()

    so maybe your message type is incorrect then, hence 404 error
    (just a guess)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search