Skip to content

Instantly share code, notes, and snippets.

@C-L-STARK
Forked from AnsonT/chat.ts
Created September 19, 2024 07:58

Revisions

  1. @AnsonT AnsonT created this gist May 15, 2023.
    35 changes: 35 additions & 0 deletions chat.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    import { NextApiRequest, NextApiResponse } from 'next'
    import { Readable } from 'node:stream'

    export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    const { authorization } = req.headers

    if (!authorization || authorization !== process.env.AUTHORIZATION_HEADER) {
    return res.status(401).json({ error: 'Unauthorized' })
    }
    const openAIUrl = process.env.OPENAI_URL as string
    const headers = new Headers()
    headers.set('Content-Type', 'application/json')
    headers.set('Authorization', `Bearer ${process.env.OPENAI_API_KEY as string}`)

    const body = JSON.stringify({
    model: 'gpt-3.5-turbo',
    max_tokens: 1024,
    temperature: 0.8,
    top_p: 1.0,
    frequency_penalty: 0,
    presence_penalty: 0,
    stream: true,
    messages: [
    { role: "user", content: req.body.input }
    ],
    })
    const response = await fetch(
    openAIUrl,
    {
    method: 'POST',
    headers,
    body,
    })
    Readable.fromWeb(response.body as any).pipe(res)
    }