ChatGPT API

Implementation of ChatGPT API

Connecting to the OpenAI API with Next

app/api/chat/router.ts
import OpenAI from 'openai';
import { NextRequest } from 'next/server';

const client = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY
});

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

        const completion = await client.chat.completions.create({
            model: 'gpt-4',
            messages: [
                {
                    role: 'system',
                    content: 'You are a coding assistant that talks like a pirate'
                },
                {
                    role: 'user',
                    content: message
                }
            ],
            temperature: 0.7,
        });

        return new Response(JSON.stringify({ response: completion.choices[0].message.content }), {
            headers: { 'Content-Type': 'application/json' },
        });
    } catch (error) {
        return new Response(JSON.stringify({ error: 'Failed to process request ' + error }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' },
        });
    }
}