Skip to content

Instantly share code, notes, and snippets.

@hubgit
Last active May 11, 2023 08:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hubgit/d825627ff7aedbb38b1ca2a6863ec63a to your computer and use it in GitHub Desktop.
Save hubgit/d825627ff7aedbb38b1ca2a6863ec63a to your computer and use it in GitHub Desktop.
Vercel Edge Function for an OpenAI API request
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