2023-05-22 10:21:51 -04:00
|
|
|
import { auth } from "@/auth";
|
2023-05-19 12:33:56 -04:00
|
|
|
import { OpenAIStream, openai } from "@/lib/openai";
|
2023-05-22 13:10:52 +02:00
|
|
|
import { prisma } from "@/lib/prisma";
|
2023-05-19 12:33:56 -04:00
|
|
|
|
2023-05-22 10:21:51 -04:00
|
|
|
export const POST = auth(async function POST(req: Request) {
|
2023-05-19 12:33:56 -04:00
|
|
|
const json = await req.json();
|
2023-05-22 10:33:40 -04:00
|
|
|
// @ts-ignore
|
|
|
|
|
console.log(req.auth); // todo fix types
|
2023-05-19 12:33:56 -04:00
|
|
|
|
|
|
|
|
const res = await openai.createChatCompletion({
|
|
|
|
|
model: "gpt-3.5-turbo",
|
|
|
|
|
messages: json.messages,
|
|
|
|
|
temperature: 0.7,
|
|
|
|
|
top_p: 1,
|
|
|
|
|
frequency_penalty: 1,
|
|
|
|
|
max_tokens: 500,
|
|
|
|
|
n: 1,
|
|
|
|
|
stream: true,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const stream = await OpenAIStream(res);
|
|
|
|
|
|
2023-05-22 13:10:52 +02:00
|
|
|
let fullResponse = "";
|
|
|
|
|
const decoder = new TextDecoder();
|
|
|
|
|
const saveToPrisma = new TransformStream({
|
|
|
|
|
transform: async (chunk, controller) => {
|
|
|
|
|
controller.enqueue(chunk);
|
|
|
|
|
fullResponse += decoder.decode(chunk);
|
|
|
|
|
},
|
|
|
|
|
flush: async () => {
|
|
|
|
|
await prisma.chat.upsert({
|
|
|
|
|
where: {
|
|
|
|
|
id: json.id,
|
|
|
|
|
},
|
|
|
|
|
create: json,
|
|
|
|
|
update: json,
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return new Response(stream.pipeThrough(saveToPrisma), {
|
2023-05-19 12:33:56 -04:00
|
|
|
status: 200,
|
|
|
|
|
headers: { "Content-Type": "text/event-stream" },
|
|
|
|
|
});
|
2023-05-22 10:21:51 -04:00
|
|
|
});
|