Created
August 16, 2024 03:49
-
-
Save MarcoF1/a1327009ee90de09bff7259086aabbac to your computer and use it in GitHub Desktop.
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
//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