#Error 400 - ChatGPT

6 messages · Page 1 of 1 (latest)

normal whale
#

I'm using the ChatGPT API in a nextJS project

My request on frontend

 const req = await fetch('/api/openai', {
                method: 'POST',
                body: JSON.stringify(conversation.messages),
             

                headers: new Headers({
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                }),
            });

My API Route

export async function POST(req: NextRequest) {
    try {
        const json = await req.json();

        const openai = new OpenAIApi(
            new Configuration({
                apiKey: process.env.OPENAI_API_KEY,
            })
        );

        const completion = await openai.createChatCompletion({
            model: 'gpt-3.5-turbo',
            messages: json,

            max_tokens: 3000,
        });

        const {
            data: { choices, id },
        } = completion;

        return new NextResponse(JSON.stringify({ choices, id }), {
            status: 200,
        });
    } catch (error) {
        return new NextResponse(JSON.stringify(error), {
            status: 500,
        });
    }
}

It works, but after a couple exchange, I get an error 400. which I think is the string formatting that's causing the error.
Checking const json = await req.json(); the string that is parsed causes string errors.

Things I've tried.

  1. Cleaning up the string conversation.messages to remove escape sequences

Would love to have help how to fix this.

#

Error 400 - ChatGPT

vestal oriole
#

can you try reducing the token size to 100-500 and try?

normal whale
craggy python
#

If the input parameters to ChatGPT is quite a lot (i.e, your prompt contains a lot of info) it is likely reaching the 4096 token limit error. Check the console when you notice these errors for max token limit reached API error spitting back from your request

vestal oriole