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.
- Cleaning up the string
conversation.messagesto remove escape sequences
Would love to have help how to fix this.