Skip to content

Instantly share code, notes, and snippets.

@MarcoF1
Created August 16, 2024 03:49
Show Gist options
  • Save MarcoF1/a1327009ee90de09bff7259086aabbac to your computer and use it in GitHub Desktop.
Save MarcoF1/a1327009ee90de09bff7259086aabbac to your computer and use it in GitHub Desktop.
//app/api/chat/route.ts
import { Configuration, OpenAIApi } from 'openai-edge'
import { OpenAIStream, StreamingTextResponse } from 'ai'
// Create an OpenAI API client (that's edge friendly!)
const config = new Configuration({
apiKey: process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(config)
// IMPORTANT! Set the runtime to edge
export const runtime = 'edge'
export async function POST(req: Request) {
// Extract the `prompt` from the body of the request
const { messages } = await req.json()
// Ask OpenAI for a streaming chat completion given the prompt
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
stream: true,
messages: messages.map((message: any) => ({
content: message.content,
role: message.role
}))
})
// Convert the response into a friendly text-stream
const stream = OpenAIStream(response)
// Respond with the stream
return new StreamingTextResponse(stream)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment