2023-06-02 11:15:04 -04:00
|
|
|
import { auth } from "@/auth";
|
|
|
|
|
import { chats, db } from "@/lib/db/schema";
|
|
|
|
|
import { openai } from "@/lib/openai";
|
|
|
|
|
import { OpenAIStream, StreamingTextResponse } from "ai-connector";
|
|
|
|
|
|
|
|
|
|
export const runtime = "edge";
|
|
|
|
|
|
|
|
|
|
export const POST = auth(async function POST(req: Request) {
|
|
|
|
|
const json = await req.json();
|
|
|
|
|
// @ts-ignore
|
|
|
|
|
console.log(req.auth); // todo fix types
|
2023-06-02 11:57:44 -04:00
|
|
|
const messages = json.messages.map((m: any) => ({
|
|
|
|
|
content: m.content,
|
|
|
|
|
role: m.role,
|
|
|
|
|
}));
|
2023-06-02 11:15:04 -04:00
|
|
|
const res = await openai.createChatCompletion({
|
|
|
|
|
model: "gpt-3.5-turbo",
|
2023-06-02 11:57:44 -04:00
|
|
|
messages,
|
2023-06-02 11:15:04 -04:00
|
|
|
temperature: 0.7,
|
|
|
|
|
top_p: 1,
|
|
|
|
|
frequency_penalty: 1,
|
|
|
|
|
max_tokens: 500,
|
|
|
|
|
n: 1,
|
|
|
|
|
stream: true,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const stream = await OpenAIStream(res, {
|
|
|
|
|
async onCompletion(completion) {
|
|
|
|
|
// @ts-ignore
|
|
|
|
|
if (req.auth?.user?.email == null) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const title = json.messages[0].content.substring(0, 20);
|
2023-06-02 11:33:17 -04:00
|
|
|
const payload = {
|
2023-06-02 11:57:44 -04:00
|
|
|
id: crypto.randomUUID(),
|
2023-06-02 11:15:04 -04:00
|
|
|
title,
|
|
|
|
|
userId: (req as any).auth?.user?.email,
|
2023-06-02 11:57:44 -04:00
|
|
|
messages: [
|
|
|
|
|
...messages,
|
|
|
|
|
{
|
|
|
|
|
content: completion,
|
|
|
|
|
role: "assistant",
|
|
|
|
|
},
|
|
|
|
|
],
|
2023-06-02 11:33:17 -04:00
|
|
|
};
|
2023-06-02 11:57:44 -04:00
|
|
|
const chat = await db
|
2023-06-02 11:33:17 -04:00
|
|
|
.insert(chats)
|
|
|
|
|
.values(payload)
|
2023-06-02 11:57:44 -04:00
|
|
|
// .onConflictDoUpdate({
|
|
|
|
|
// target: payload.id,
|
|
|
|
|
// set: payload,
|
|
|
|
|
// })
|
|
|
|
|
.returning();
|
|
|
|
|
console.log(chat);
|
2023-06-02 11:15:04 -04:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return new StreamingTextResponse(stream);
|
|
|
|
|
});
|