-
-
Save C-L-STARK/e27c63ccfcbba056ebb93f41eda9cad4 to your computer and use it in GitHub Desktop.
Stream OpenAI response though NextJS API route
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment