2023-03-11 12:54:24 +00:00
|
|
|
import type { ChatRequest } from "../chat/typing";
|
|
|
|
import { createParser } from "eventsource-parser";
|
|
|
|
import { NextRequest } from "next/server";
|
|
|
|
|
|
|
|
const apiKey = process.env.OPENAI_API_KEY;
|
|
|
|
|
2023-03-11 14:43:15 +00:00
|
|
|
async function createStream(payload: ReadableStream<Uint8Array>) {
|
2023-03-11 12:54:24 +00:00
|
|
|
const encoder = new TextEncoder();
|
|
|
|
const decoder = new TextDecoder();
|
|
|
|
|
|
|
|
const res = await fetch("https://api.openai.com/v1/chat/completions", {
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
Authorization: `Bearer ${apiKey}`,
|
|
|
|
},
|
|
|
|
method: "POST",
|
2023-03-11 14:35:38 +00:00
|
|
|
body: payload,
|
2023-03-11 12:54:24 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const stream = new ReadableStream({
|
|
|
|
async start(controller) {
|
|
|
|
function onParse(event: any) {
|
|
|
|
if (event.type === "event") {
|
|
|
|
const data = event.data;
|
|
|
|
// https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream
|
|
|
|
if (data === "[DONE]") {
|
|
|
|
controller.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
const json = JSON.parse(data);
|
|
|
|
const text = json.choices[0].delta.content;
|
|
|
|
const queue = encoder.encode(text);
|
|
|
|
controller.enqueue(queue);
|
|
|
|
} catch (e) {
|
|
|
|
controller.error(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const parser = createParser(onParse);
|
|
|
|
for await (const chunk of res.body as any) {
|
|
|
|
parser.feed(decoder.decode(chunk));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
return stream;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function POST(req: NextRequest) {
|
|
|
|
try {
|
2023-03-11 14:43:15 +00:00
|
|
|
const stream = await createStream(req.body!);
|
2023-03-11 12:54:24 +00:00
|
|
|
return new Response(stream);
|
|
|
|
} catch (error) {
|
2023-03-19 14:13:00 +00:00
|
|
|
console.error("[Chat Stream]", error);
|
2023-03-11 12:54:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const config = {
|
|
|
|
runtime: "edge",
|
|
|
|
};
|