2023-03-11 12:54:24 +00:00
|
|
|
import { createParser } from "eventsource-parser";
|
|
|
|
import { NextRequest } from "next/server";
|
2023-03-29 17:45:26 +00:00
|
|
|
import { requestOpenai } from "../common";
|
2023-03-11 12:54:24 +00:00
|
|
|
|
2023-03-26 11:58:25 +00:00
|
|
|
async function createStream(req: NextRequest) {
|
2023-03-11 12:54:24 +00:00
|
|
|
const encoder = new TextEncoder();
|
|
|
|
const decoder = new TextDecoder();
|
|
|
|
|
2023-03-29 17:45:26 +00:00
|
|
|
const res = await requestOpenai(req);
|
2023-03-11 12:54:24 +00:00
|
|
|
|
2023-04-02 19:14:53 +00:00
|
|
|
const contentType = res.headers.get("Content-Type") ?? "";
|
|
|
|
if (!contentType.includes("stream")) {
|
|
|
|
const content = await (
|
|
|
|
await res.text()
|
|
|
|
).replace(/provided:.*. You/, "provided: ***. You");
|
|
|
|
console.log("[Stream] error ", content);
|
|
|
|
return "```json\n" + content + "```";
|
|
|
|
}
|
|
|
|
|
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) {
|
2023-04-10 15:13:20 +00:00
|
|
|
parser.feed(decoder.decode(chunk, { stream: true }));
|
2023-03-11 12:54:24 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
return stream;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function POST(req: NextRequest) {
|
|
|
|
try {
|
2023-03-26 11:58:25 +00:00
|
|
|
const stream = await createStream(req);
|
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-04-05 19:19:33 +00:00
|
|
|
return new Response(
|
|
|
|
["```json\n", JSON.stringify(error, null, " "), "\n```"].join(""),
|
|
|
|
);
|
2023-03-11 12:54:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-21 05:03:02 +00:00
|
|
|
export const runtime = "experimental-edge";
|