Last active
May 11, 2023 08:35
-
-
Save hubgit/d825627ff7aedbb38b1ca2a6863ec63a to your computer and use it in GitHub Desktop.
Vercel Edge Function for an OpenAI API request
This file contains 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 type { NextRequest } from 'next/server' | |
import { createParser } from 'eventsource-parser' | |
export const config = { | |
runtime: 'edge', | |
} | |
export default async function handler(req: NextRequest) { | |
const encoder = new TextEncoder() | |
const decoder = new TextDecoder() | |
const readableStream = new ReadableStream({ | |
async start(controller) { | |
const parser = createParser((event) => { | |
if (event.type === 'event') { | |
if (event.data === '[DONE]') { | |
controller.close() | |
} else { | |
const data = JSON.parse(event.data) | |
controller.enqueue(encoder.encode(data.choices[0].delta.content)) | |
} | |
} | |
}) | |
const response = await fetch('https://api.openai.com/v1/chat/completions', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, | |
}, | |
body: JSON.stringify({ | |
model: 'gpt-4', | |
messages: [ | |
{ role: 'system', content: system }, | |
{ role: 'user', content: user }, | |
], | |
stream: true, | |
temperature: 0, | |
}), | |
}) | |
if (!response.ok) { | |
console.log(await response.text()) | |
throw new Error() | |
} | |
for await (const chunk of response.body as any) { | |
parser.feed(decoder.decode(chunk)) | |
} | |
}, | |
}) | |
return new Response(readableStream, { | |
headers: { 'Content-Type': 'text/plain; charset=UTF-8' }, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment